package com.example.msg;

import android.content.SharedPreferences;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;

import com.example.msg.utils.HttpUtils;
import com.just.agentweb.AgentWeb;

public class JsInvorkCall {
    public static final String TAG = "HELLO-JsInvorkCall:";
    private SharedPreferences sharedPreferences;
    private AgentWeb agentWeb;
    public JsInvorkCall(){

    }
    public JsInvorkCall(SharedPreferences sp,AgentWeb aw){
        sharedPreferences=sp;
        agentWeb=aw;
    }
    @JavascriptInterface
    public void setItem(String name,String value){
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(name,value);
        editor.apply();
    }
    @JavascriptInterface
    public String getItem(String name){
        return sharedPreferences.getString(name,null);
    }

    @JavascriptInterface
    public boolean getClientState(){
        return Client.isRun;
    }
    @JavascriptInterface
    public void startClient(){
        Client.start();
    }
    @JavascriptInterface
    public void stopClient(){
        Client.stop();
    }

    @JavascriptInterface
    public void httpGetAsync(String url,String token,String call){

        if(call!=null){
            new Thread(){
                @Override
                public void run() {
                    try{
                        String json= HttpUtils.get(url,token);
                        agentWeb.getJsAccessEntrace().quickCallJs(call,json);
                    }catch (Exception e){
                        e.printStackTrace();
                        agentWeb.getJsAccessEntrace().quickCallJs(call,"{\"cood\":-1,\"msg\":\""+e.getMessage()+"\"}");
                    }
                }
            }.start();
        }
    }


    @JavascriptInterface
    public void httpPostAsync(String url,String param,String token,String call){

        if(call!=null){
            new Thread(){
                @Override
                public void run() {
                    try{
                        String json= HttpUtils.post(url,token,param);
                        agentWeb.getJsAccessEntrace().quickCallJs(call,json);
                    }catch (Exception e){
                        e.printStackTrace();
                        agentWeb.getJsAccessEntrace().quickCallJs(call,"{\"cood\":-1,\"msg\":\""+e.getMessage()+"\"}");
                    }
                }
            }.start();
        }
    }
    @JavascriptInterface
    public String httpGet(String url,String token){
        String json= HttpUtils.get(url,token);
        return json;
    }
    @JavascriptInterface
    public String httpPost(String url,String json,String token){
        return HttpUtils.post(url,token,json);
    }

}
